/**
 * 
 */
package controllers;

import java.util.Map;

import javax.validation.Valid;

import models.LoginModel;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author hoannguyen
 *
 */
@Controller
public class LoginController {
	
	/**
	 * For logging
	 */
	private static final Logger LOG = Logger.getLogger(LoginController.class);
	
	/**
	 * Handle for the first time the login page is loaded.
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(method = RequestMethod.GET, value = "/login")
	public String loadForm(Map model){
		
		// Log
		if(LOG.isDebugEnabled()){
			LOG.info("loadForm:");
		}
		
		// Add a loginModel before rendering the JSP file
		LoginModel loginModel = new LoginModel();
		model.put("loginModel", loginModel);
		
		// Return to the view
		return "login-validation";
	}
	
	/**
	 * Handle for the submit of the login form.
	 * @param hLogin bound values
	 * @param result validation result
	 * @param map 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(method = RequestMethod.POST, value = "/login")
	public String processForm(
			@Valid @ModelAttribute("loginModel") LoginModel loginModel,
			BindingResult result, Map map) {
		
		// Log
		if(LOG.isDebugEnabled()){
			LOG.error("processForm:");
		}
		
		// Check if the user input values are invalid
		if (result.hasErrors()) {
			return "login-validation";
		}
		
		// Declare the expected values
		String userName = "username";
		String password = "password";
		if (!loginModel.getUserName().trim().equals(userName) 
				|| !loginModel.getPassword().trim().equals(password)) {
			return "login-validation";
		}
		
		// Return to the successful page
		LoginModel successfulModel = new LoginModel(loginModel);
		map.put("login", successfulModel);
		return "login-success";
	}
}
